// app/service/aiService.js
const egg = require('egg');
class AIService extends egg.Service {
  async queryAI() {
    const { ctx, app } = this;
    const { apiKey, apiUrl } = app.config.bailianAI;

    try {
      // 是否响应流失数据
      const isResponseStream = ctx.request.header['x-response-stream'];
      // 是否是文件流上传
      const isStreamRequest = ctx.request.header['content-type'].indexOf('multipart/form-data') > -1;
      // 请求参数配置
      const requestOptions = {
        method: ctx.method,
        data: ctx.request.body,
        headers: {
          Authorization: `Bearer ${apiKey}`,
          ...ctx.request.header,
          host: '', // 存在 host 时，百炼大模型 API 限制了 .aliyuncs.com 域名才能请求，所以这里直接置空 host
        },
      };
      if (isStreamRequest) {
        // 支持文件流上传
        requestOptions.stream = ctx.req;
      }
      if (isResponseStream) {
        // 支持流失数据响应
        requestOptions.streaming = !!isResponseStream;
      }
      // 发起请求
      const response = await ctx.curl(apiUrl, requestOptions);
      // 设置响应头
      ctx.status = response.status;
      ctx.set('content-type', response.headers['content-type']);

      // 返回响应
      return isResponseStream ? response.res : response.data;
    } catch (error) {
      this.logger.error('Error querying AI service:', error);
      throw error;
    }
  }
}

module.exports = AIService;
